from time import sleep

import requests
import random
import json
from hashlib import md5

# Set your own appid/appkey.
appid = '20161019000030417'
appkey = 'TcAihQsIFCsOdnA14NyA'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'auto'
to_lang =  'spa'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

operateCount = 0

# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

operatedCount = 0


#读取源文件
with open(r'C:\Users\adind\Desktop\i18n\source.txt',mode='r',encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:

        #如果line未必包含\r\n，则去除
        line = line.strip()
        #读取到文件尾则跳出

        if line.find("=") == -1:
            with open(r'C:\Users\adind\Desktop\i18n\dest.txt', mode='a+', encoding='utf-8') as f1:
                f1.write(line + "\n")
            continue
        #当读取的行不为空时
        parts = line.split("=")
        #翻译
        query = parts[1]

        retryTimeAPI = 10

        #输出目标文件
        while True:
            try:
                salt = random.randint(32768, 65536)
                sign = make_md5(appid + query + str(salt) + appkey)

                # Build request
                headers = {'Content-Type': 'application/x-www-form-urlencoded'}
                payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

                # Send request
                r = requests.post(url, params=payload, headers=headers)
                result = r.json()

                # Show response
                #print(json.dumps(result, indent=4, ensure_ascii=False))
                #取得翻译后的结果
                retryWriteFile = 3
                while True:
                    try:
                        with open(r'C:\Users\adind\Desktop\i18n\dest.txt', mode='a+', encoding='utf-8') as f1:
                            f1.write(parts[0] + "=" + result['trans_result'][0]['dst'] + "\n")
                        break
                    except Exception as e1:
                        retryWriteFile -= 1
                        if retryWriteFile > 0:
                            continue
                        else:
                            break

                operatedCount += 1
                print("已完成",operatedCount)
                break
            except Exception as e:
                print("error,",e)
                retryTimeAPI-= 1

                if retryTimeAPI > 0:
                    sleep(0.5)
                    print("retry")
                    continue
                else:
                    f1.write(parts[0] + "=##失败")
                    break

        operateCount += 1